Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[12.x] Improved algorithm for Number::pairs() #52641

Merged
merged 3 commits into from
Sep 4, 2024

Conversation

hotmeteor
Copy link
Contributor

@hotmeteor hotmeteor commented Sep 4, 2024

Description

A short while ago I submitted a PR for a new Number macro called pairs(). However, while using it in a production app I realized that it didn't perform exactly how I intended because it was missing an important argument: the starting value.

This PR introduces a new $start argument, which improves the behavior of the method to match expectations. Before, the $offset argument was being reused for both but this was conflating things and resulted in weird offsets. With a distinct $start argument both the initial value and the increment between pairs can be individually controlled.

Note: This is a breaking change due to a new 3rd argument!

Before

$output = Number::pairs(2500, 1000, 1); // Start at 1, offset also 1

// [[1, 1000], [1001, 2000], [2001, 2500]]

$output = Number::pairs(2500, 1000, 0); // Start at 0 offset also 0

// [[0, 1000], [1000, 2000], [2000, 2500]]

While this looks fine, you'll notice that you can't get the values to end in 999, ie. [1, 999] or [0, 999]. This means that your offset/pagination value must always start with 1, which may be incorrect.

After

$output = Number::pairs(2500, 1000, 1, 0); // Start at 1, offset 0

// [[1, 1001], [1001, 2001], [2001, 2500]]

$output = Number::pairs(2500, 1000, 1, 1); // Start at 1, offset 1

// [[1, 1000], [1001, 2000], [2001, 2500]]

$output = Number::pairs(2500, 1000, 0, 0); // Start at 0, offset 0

// [[0, 1000], [1000, 2000], [2000, 2500]]

$output = Number::pairs(2500, 1000, 0, 1); // Start at 0, offset 1

// [[0, 999], [1000, 1999], [2000, 2500]]

Now, starting value and offsets are distinct allowing for the proper pairing.

@taylorotwell taylorotwell merged commit 2f4ebf1 into laravel:master Sep 4, 2024
30 of 31 checks passed
@hotmeteor hotmeteor deleted the better-number-pairs branch September 4, 2024 14:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants